/// describe
///
/// created by hujintao
/// created at 2021/5/20
//
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutterappdriver/utils/adaption_util.dart';
import 'package:flutterappdriver/utils/toast.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {
  const WebViewPage({Key? key}) : super(key: key);

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  WebViewController? _controller;

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('WebView'),
        actions: [
          InkWell(
            onTap: () {
              _controller
                  ?.evaluateJavascript('changeBg("#55c9c4")')
                  ?.then((result) {
                // You can handle JS result here.
              });
            },
            child: Container(
              child: Center(
                child: Text(
                  'Flutter修改JS背景色',
                  style: TextStyle(fontSize: 16),
                ),
              ),
              margin: EdgeInsets.only(right: AdaptationUtils.setWidth(20)),
            ),
          )
        ],
        // This drop down menu demonstrates that Flutter widgets can be shown over the web view.
      ),
      // We're using a Builder here so we have a context that is below the Scaffold
      // to allow calling Scaffold.of(context) so we can show a snackbar.
      body: Builder(builder: (BuildContext context) {
        return WebView(
          initialUrl:
              'file:///android_asset/flutter_assets/assets/webview/index.html',
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _controller = webViewController;
          },
          onProgress: (int progress) {
            print("WebView is loading (progress : $progress%)");
          },
          javascriptChannels: <JavascriptChannel>[
            _javascriptChannel(context),
          ].toSet(),
          navigationDelegate: (NavigationRequest request) {
            if (request.url.startsWith('https://www.youtube.com/')) {
              print('blocking navigation to $request}');
              return NavigationDecision.prevent;
            }
            print('allowing navigation to $request');
            return NavigationDecision.navigate;
          },
          onPageStarted: (String url) {
            print('Page started loading: $url');
          },
          onPageFinished: (String url) {
            print('Page finished loading: $url');
          },
          gestureNavigationEnabled: true,
        );
      }),
      floatingActionButton: favoriteButton(),
    );
  }

  JavascriptChannel _javascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'hk',
        onMessageReceived: (JavascriptMessage message) {
          if (message.message == "getIsLogin") {
            this.isLogin();
          } else {
            Toast.heartShow("接收到来自JS的消息：\n${message.message}");
          }
        });
  }

  isLogin() {
    bool isLogin = true;
    String script = "window.isLogin=$isLogin";
    _controller?.evaluateJavascript("$script");
  }

  Widget favoriteButton() {
    return FutureBuilder<WebViewController>(builder:
        (BuildContext context, AsyncSnapshot<WebViewController> controller) {
      if (controller.hasData) {
        return FloatingActionButton(
          onPressed: () async {
            final String url = (await controller.data!.currentUrl())!;
            // ignore: deprecated_member_use
            Scaffold.of(context).showSnackBar(
              SnackBar(content: Text('Favorited $url')),
            );
          },
          child: const Icon(Icons.favorite),
        );
      }
      return Container();
    });
  }
}
